package com.atls.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atls.oss.service.OssService;
import com.atls.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {

    @Override
    public String uploadAvatar(MultipartFile file) {
        //获取阿里云存储相关常量
        String endPoint= ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

        try {
            //创建oss实例
            OSS ossClient = new OSSClientBuilder().build(endPoint,accessKeyId,accessKeySecret);
            //上传文件流
            InputStream inputStream = file.getInputStream();
            //获取文件名称
            String filename = file.getOriginalFilename();

            //1.在文件里添加唯一随机值
            String uuid = UUID.randomUUID().toString().replace("-","");
            filename=uuid+filename;

            //2.文件按日期分类
            String datePath = new DateTime().toString("yyyy/MM/dd");
            filename=datePath+"/"+filename;

            //实现文件上传
            ossClient.putObject(bucketName,filename,inputStream);

            //关闭
            ossClient.shutdown();

            //把文件路径返回
            String url="https://"+bucketName+"."+endPoint+"/"+filename;
            return url                ;
        }catch (Exception e){
              e.printStackTrace();
              return null;
        }

    }
}
